var v = new Vue({
    el: "#page", data: {
        amount: 0,
        terName: null,
        remark: null,
        token: null,
        merName: null,
        showRemark: false,
        inputRemark: null,
        begin: 0,
        sn: null,
        tenant_no: null,
        openid: null,
        isShowKey: false,
        remarkLength: 0,
              is_remarks: 0,
    }, created() {
        this.token = getUrlParam("token")
        this.merName = getUrlParam("merName")
        this.terName = getUrlParam("terName")
        this.sn = getUrlParam("sn")
        this.tenant_no = getUrlParam("tenant_no")
        this.openid = getUrlParam("openid")
        var amount = getUrlParam("amount")
         this.is_remarks = getUrlParam("is_remarks")
        if (amount) {
            this.amount = amount;
        } else {
            this.isShowKey = true
        }
        console.log(this.token);
        console.log(this.merName);
        console.log(this.terName);
        console.log(this.tenant_no);
    }, methods: {
        async beginPay() {

            if (!this.amount == null || Number(this.amount) == 0) {
                this.$toast('消费金额不能为0');
                return
            }

            if (Number(this.is_remarks) == 1 && this.remark == null) {
                this.$toast('请输入付款备注');
                return
            }


            let remark = this.remark;
            if (remark == null) remark = "";
            if (this.begin == 1) {
                if (!this.isShowKey) this.$toast(this.errMsg);
                return
            }
            this.begin = 1

            var plat = await postApi("/plat", {
                mersn: this.tenant_no,
            })

            if (plat == "error") {
                this.$toast("请核对商户信息");
            }
            var openids=''; //document.getElementById('zfbUserId').value
            var zfbUserId=document.getElementById('zfbUserId').value;
            if(typeof this.openid !== 'undefined' && this.openid !== null && this.openid !== ''){
            	  openids=this.openid;
            	} else  if(typeof zfbUserId !== 'undefined' && zfbUserId !== null && zfbUserId !== ''){
            	  openids=zfbUserId;
            	}

           //this.openid

            var res = await postApi("/pay", {
                sn: this.sn,
                remark: this.remark,
                tradeMoney: this.regYuanToFen(this.amount, 100),
                tenant_no: this.tenant_no,
                openid: openids,
                payType: plat,
            })


            if (res.data.tradeStatus == "FAILURE") {
                this.errMsg = res.msg
                this.$toast(res.msg);
                if(res.msg.con)
               // alert(res.msg);
                if (this.isShowKey) this.begin = 0;
                return
            }
            alert(res.data.tradeStatus);
            alert(res.msg);

            if (res.data.tradeStatus == "UNKNOW"&&!hasSuccess(res.msg)) {
                this.errMsg = res.msg
                this.$toast(res.msg);
                if(res.msg.con)
                    // alert(res.msg);
                    if (this.isShowKey) this.begin = 0;
                return
            }


            var _this = this
            if (plat == 2) {
                var args = JSON.parse(res.data.payInfo)
                console.log(args)
                callPay(function () {
                    try {
                        WeixinJSBridge.invoke('getBrandWCPayRequest', {
                            "appId": args.appId, //公众号名称，由商户传入
                            "timeStamp": args.timeStamp, //时间戳，自1970年以来的秒数
                            "nonceStr": args.nonceStr, //随机串
                            "package": args.package, "signType": args.signType, //微信签名方式：
                            "paySign": args.paySign //微信签名
                        }, function (res) {
                            if (res.err_msg == "get_brand_wcpay_request:cancel") {
                                window.location.href = "error.html?msg=" + decodeURI("已取消交易")
                            } else if (res.err_msg == "get_brand_wcpay_request:fail") {
                                window.location.href = "error.html?msg=" + decodeURI("已取消交易")
                            } else {
                                window.location.href = "error.html?msg=" + decodeURI(res.err_msg)
                            }
                        });
                    } catch (e) {
                        _this.$toast.fail(e);
                    }
                })
                return
            }

            if (this.isShowKey) {
                console.log(res.data)
                this.begin = 0;
                if (res.data.codeUrl == null || res.data.codeUrl == "") {
                	  if(res.data.tradeNo!=null&&res.data.tradeNo!=''){
                	  	  tradePay(res.data.tradeNo);
                	  	}else {
                	  		  this.$toast(res.msg);
                	  	}

                } else {
                    window.location.href = res.data.codeUrl;
                }
            }

        },

        getNum(val) {
            var amount = this.amount;//原金额

            var d = amount + val;
            if (d == '.') d = '0.';

            //转数字失败，比如2个小数点
            var num = Number(d);
            if (isNaN(num)) return;
            var dotIndex = d.toString().indexOf('.');
            var a = '';
            var b = '';
            if (dotIndex === -1)//没有小数点
            {
                if (d.length > 7) return;
                a = d;
            } else//有小数点
            {
                a = d.substr(0, dotIndex);
                b = d.substr(dotIndex + 1, d.length - dotIndex - 1);
                if (b.length > 2) b = b.substr(0, 2);
            }
            var a1 = parseInt(a);
            var d1 = dotIndex === -1 ? '' + a1 : a1 + '.' + b;
            this.amount = d1;
        }, delNum(val) {
            var amount = this.amount;
            if (amount.length === 0) return; else amount = amount.substring(0, amount.length - 1);
            this.amount = amount
        }, confirmRemark() {
            this.showRemark = false
            let patrn = /[`~!#&=?]/
            if (patrn.test(this.inputRemark)) {
                this.$toast("备注请勿含有特殊字符")
                return;

            }
            this.remark = this.inputRemark
        }, /*
         * @Description: 监听输入框
         * @params: content
         */
        inputEvent(val) {
            this.remarkLength = this.inputRemark.length
        },


        regYuanToFen(yuan, digit) {
            var m = 0, s1 = yuan.toString(), s2 = digit.toString();
            try {
                m += s1.split(".")[1].length
            } catch (e) {
            }
            try {
                m += s2.split(".")[1].length
            } catch (e) {
            }
            return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
        }

    }
})

function callPay(callback) {
    if (typeof WeixinJSBridge == "undefined") {
        if (document.addEventListener) {
            document.addEventListener('WeixinJSBridgeReady', callback, false);
        } else if (document.attachEvent) {
            document.attachEvent('WeixinJSBridgeReady', callback);
            document.attachEvent('onWeixinJSBridgeReady', callback);
        }
    } else {
        callback();
    }
}

 // 由于js的载入是异步的，所以可以通过该方法，当AlipayJSBridgeReady事件发生后，再执行callback方法
     function ready(callback) {
         if (window.AlipayJSBridge) {
             callback && callback();
         } else {
             document.addEventListener('AlipayJSBridgeReady', callback, false);
         }
     }
   function tradePay(tradeNO) {

        ready(function(){
             // 通过传入交易号唤起快捷调用方式(注意tradeNO大小写严格)
             AlipayJSBridge.call("tradePay", {
              tradeNO: tradeNO
             }, function (data) {
                 log(JSON.stringify(data));
                 if ("9000" == data.resultCode) {
                     console.log('支付成功');
                 }
             });
        });
    }

function hasSuccess(str) {
    // 包含“成功” 或 包含“success”，则返回true
    return str.includes('成功') || str.includes('success')|| str.includes('SUCCESS');
}
